﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using ERP_RORZE_SYSTEM;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ERP_RORZE_DLL.Assembly
{
    public partial class frm_Add_F4MaterialReceive : Form
    {
        private DataSet ds;
        private DataViewManager dsView;

        private DataSet ds2;
        private DataViewManager dsView2;
        
        public frm_Add_F4MaterialReceive()
        {
            InitializeComponent();
            this.mySetting = new INISettings();
            this.myConnection = new SqlConnection(mySetting.SQLConnectionString);
            this.ds = new DataSet("Staff");
            this.ds2 = new DataSet("Material");
            this.addDate.EditValue = DateTime.Now;

            LoadStaffList();
            LoadMaterialList();
            LoadSupplierList();
        }
                
        /// <summary>
        /// Load Staff List
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void LoadStaffList()
        {
            try
            {
                myConnection.Open();
                SqlCommand cmd_sql = myConnection.CreateCommand();
                cmd_sql.CommandText = "SELECT [StaffID], [StaffName] FROM [222_Staff]"
                    + " WHERE [StopDate] IS NULL ORDER BY StaffID";
                SqlDataAdapter da1 = new SqlDataAdapter();
                da1.SelectCommand = cmd_sql;
                da1.TableMappings.Add("Table", "Staff");
                da1.Fill(ds);
                dsView = ds.DefaultViewManager;
                cmd_sql.Dispose();
                myConnection.Close();

                this.staffID.DataSource = dsView;
                this.staffID.DisplayMember = "Staff.StaffID";
                this.staffID.ValueMember = "Staff.StaffID";
                this.staffID.AutoCompleteSource = AutoCompleteSource.ListItems;

                this.staffName.DataBindings.Add("Text", dsView, "Staff.StaffName");
            }
            catch (Exception ex)
            {
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
                MessageBox.Show(ex.Message);
            }
        }

        /// <summary>
        /// Load Material List
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void LoadMaterialList()
        {
            try
            {
                myConnection.Open();
                SqlCommand cmd_sql = myConnection.CreateCommand();
                cmd_sql.CommandText = "SELECT [PartNo], [PartEnglishName] FROM [222_Part] WHERE [PType]='P'";
                SqlDataAdapter da1 = new SqlDataAdapter();
                da1.SelectCommand = cmd_sql;
                da1.TableMappings.Add("Table", "Material");
                da1.Fill(ds2);
                dsView2 = ds2.DefaultViewManager;
                cmd_sql.Dispose();
                myConnection.Close();

                this.materialNo.DataSource = dsView2;
                this.materialNo.DisplayMember = "Material.PartNo";
                this.materialNo.ValueMember = "Material.PartNo";
                this.materialNo.AutoCompleteSource = AutoCompleteSource.ListItems;

                this.materialName.DataBindings.Add("Text", dsView2, "Material.PartEnglishName");
            }
            catch (Exception ex)
            {
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
                MessageBox.Show(ex.Message);
            }
        }

        /// <summary>
        /// Load Supplier List
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void LoadSupplierList()
        {
            try
            {
                myConnection.Open();
                SqlCommand sql_cmd = myConnection.CreateCommand();
                sql_cmd.CommandText = "SELECT SupplierID, SupplierName FROM [231_Supplier]";
                SqlDataReader dataReader = sql_cmd.ExecuteReader();
                while (dataReader.Read())
                {
                    ComboboxItem item = new ComboboxItem();
                    item.Text = dataReader["SupplierID"].ToString();
                    item.Value = dataReader["SupplierID"].ToString();
                    this.supplierID.Properties.Items.Add(item);
                }

                dataReader.Close();
                sql_cmd.Dispose();
                myConnection.Close();
            }
            catch
            {
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
            }
        }

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            this.Dispose();
        }        
        
        ///////////////////////////
        /// When Click Add Button
        ///////////////////////////        
        private void buttonAdd_Click(object sender, EventArgs e)
        {
            string err = null;
            DateTime adddate = new DateTime();
            string materialno = null, staffid = null, invoiceno = null, supplierid = null, remark = null;
            float quantity = 0;

            if (string.IsNullOrEmpty(this.addDate.EditValue.ToString()))
            {
                err = "Please select Date.";
            }
            else
            {
                adddate = DateTime.Parse(this.addDate.EditValue.ToString());
            }

            if (string.IsNullOrEmpty(err))
            {
                if (string.IsNullOrEmpty(this.staffID.Text.Trim()))
                {
                    err = "Please select Staff ID";
                }
                else
                {
                    staffid = this.staffID.Text.Trim();
                }
            }

            if (string.IsNullOrEmpty(err))
            {
                if (string.IsNullOrEmpty(this.materialNo.Text.Trim()))
                {
                    err = "Please select Material No.";
                }
                else
                {
                    materialno = this.materialNo.Text.Trim();
                }
            }

            if (string.IsNullOrEmpty(err))
            {
                if (string.IsNullOrEmpty(this.invoiceNo.Text.Trim()))
                {
                    err = "Please enter Invoice No.";
                }
                else
                {
                    invoiceno = this.invoiceNo.Text.Trim();
                }
            }

            if (string.IsNullOrEmpty(err))
            {
                if (this.supplierID.SelectedIndex < 0)
                {
                    err = "Please select Supplier ID";
                }
                else
                {
                    ComboboxItem item = (ComboboxItem)this.supplierID.SelectedItem;
                    supplierid = item.Value.ToString();
                }
            }

            if (string.IsNullOrEmpty(err))
            {
                if (string.IsNullOrEmpty(this.quantityValue.Text.Trim()))
                {
                    err = "Please enter Quantity";
                }
                else
                {
                    if (float.TryParse(this.quantityValue.Text.Trim(), out quantity))
                    {
                        if (quantity <= 0)
                        {
                            err = "Quantity value must be greater than 0";
                        }
                    }
                    else
                    {
                        err = "Invalid quantity";
                    }
                }
            }

            if (string.IsNullOrEmpty(err))
            {
                remark = this.remarkText.Text.Trim();               

                try
                {
                    myConnection.Open();
                    SqlCommand sql_cmd = myConnection.CreateCommand();
                    sql_cmd.CommandText = "INSERT INTO [444_MaterialF4Receive] ([InvoiceNo], [MaterialID],"
                        + " [MaterialF4ReceiveQuantity], [MaterialF4ReceiveDate], [Remark], [StaffID], [SupplierID])"
                        + " VALUES ('" + invoiceno + "', '" + materialno + "', " + quantity + ","
                        + " @adddate, '" + remark + "', '" + staffid + "', '" + supplierid + "')";
                    sql_cmd.Parameters.Add("@adddate", SqlDbType.DateTime).Value = adddate.Date;
                    sql_cmd.ExecuteNonQuery();
                    sql_cmd.Dispose();
                    myConnection.Close();
                    MessageBox.Show("Material Receive was added succeedfully.");
                    ClearForm();
                }
                catch
                {
                    if (myConnection.State == ConnectionState.Open)
                    {
                        myConnection.Close();
                    }
                    MessageBox.Show("Cannot add Material Receive.");
                }
            }
            else
            {
                MessageBox.Show(err);
            }
        }

        private void ClearForm()
        {
            //this.supplierID.SelectedIndex = -1;
            this.quantityValue.Text = "";
            //this.invoiceNo.Text = "";            
            this.remarkText.Text = "";
        }
    }
}
